const crypto = require('crypto');
const axios = require('axios');
const dao = require('../dao/dao');
const mchNo = 2025074685;   //商户号
const currency = 'usd';  //币种
const key = '2FdM5M1B4A21k1385973SZq9ck1rM3E9';     // 商户密钥
const apiUrl = 'https://www.wiwiusonepayout.com/api/pay/create'; // 正式接口

let orderCounter = 0;
// 开始充值
async function startRecharge(data, ip) {

    const rechargeType = data.rechargeType;  //充值方式
    const amount = data.amount;
    const playerId = data.playerId;
    const giftCoin = data.giftCoin;

    const mchOrderNo = generateOrderId();  //商户订单号
    const wayCode = rechargeType;          //支付方式

    const notifyUrl = "http://8.138.47.15:10000/rechargeNotify"

    const timestamp = Date.now();

    //构建参数列表
    const params = {
        mchNo: mchNo,
        mchOrderNo: mchOrderNo,
        amount: amount * 100,
        currency: currency,
        wayCode: wayCode,
        clientIp: ip,
        notifyUrl: notifyUrl,
        timestamp: timestamp,
        signType: "MD5",
        extParam: giftCoin,  //拓展参数   拓展参数里放的是赠送金币数
        wayParam: {                             //支付方式参数
            clientId: playerId
        },
    };

    // 签名
    const signStr = getSignStr(params, key);
    const sign = getSign(signStr, params.signType);
    params.sign = sign;


    try {
        const response = await axios.post(apiUrl, params, {
            headers: { 'Content-Type': 'application/json' }
        });
        if (response.data.msg == 'SUCCESS') {
            let info = response.data.data
            dao.insertRechargeOrder_WiwiPay(params, info.cashierUrl, data.isFirst, info.payOrderNo, response.data.sign);
            return response.data;
        } else {
            return false;
        }
    } catch (error) {
        console.error('提现请求错误:', error.message);
        if (error.response) {
            console.error('接口返回状态码:', error.response.status);
            console.error('接口返回数据:', error.response.data);
        }
        return false;
    }


}

//生成订单号
function generateOrderId() {
    const date = new Date();
    const dateStr = date.getFullYear().toString() +
        String(date.getMonth() + 1).padStart(2, '0') +
        String(date.getDate()).padStart(2, '0') +
        String(date.getHours()).padStart(2, '0') +
        String(date.getMinutes()).padStart(2, '0') +
        String(date.getSeconds()).padStart(2, '0');

    // 自增序列，防止同一秒内重复
    orderCounter = (orderCounter + 1) % 100000; // 5 位流水号
    const counterStr = String(orderCounter).padStart(5, '0');

    return dateStr + counterStr;
}

// 生成签名字符串（按键名排序）
function getSignStr(params, key) {
    const sorted = sortValueRecursively(params);
    const entries = Object.entries(sorted)
        .filter(([k]) => k.toLowerCase() !== 'sign')
        .map(([k, v]) => [k, typeof v === 'object' ? JSON.stringify(v) : v])
        .sort(([a], [b]) => a.localeCompare(b));
    const queryString = entries.map(([k, v]) => `${k}=${v}`).join('&');
    return `${queryString}&key=${key}`;
}

// 计算签名
function getSign(signStr, signType) {
    let hash;
    switch (signType.toUpperCase()) {
        case 'MD5':
            hash = crypto.createHash('md5').update(signStr).digest('hex');
            break;
        case 'SHA1':
            hash = crypto.createHash('sha1').update(signStr).digest('hex');
            break;
        case 'SHA256':
            hash = crypto.createHash('sha256').update(signStr).digest('hex');
            break;
        default:
            throw new Error(`Unsupported sign type: ${signType}`);
    }
    return hash.toUpperCase();
}


// 对象递归排序
function sortValueRecursively(value) {
    if (Array.isArray(value)) {
        return value.map(item => sortValueRecursively(item));
    } else if (value && typeof value === 'object') {
        return Object.fromEntries(
            Object.entries(value)
                .map(([k, v]) => [k, sortValueRecursively(v)])
                .sort(([ak], [bk]) => ak.localeCompare(bk))
        );
    }
    return value;
}

module.exports = {
    startRecharge
}